<template>
  <!-- 添加或修改付款申请单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-row :gutter="24">
      <el-col :span="8">
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="采购日期" prop="applyTime">
                  <el-date-picker clearable
                                  v-model="form.applyTime"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  placeholder="请选择申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票编号" prop="invoiceCode">
                  <el-input v-model="form.invoiceCode" placeholder="请输入发票编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票照片" prop="invoicePhoto">
                  <file-upload v-model="form.invoicePhoto"></file-upload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="采购类型" prop="ywType">
                  <el-select v-model="form.ywType" placeholder="请选择采购类型" clearable disabled>
                    <el-option v-for="dict in dict.type.caigou_type"
                               :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="采购金额:" prop="totalMoney">
                  <el-input-number v-model="form.totalMoney" :precision="2"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="供应商:" prop="supplierId">
                  <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier"
                             style="width: 260px">
                    <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                               :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="开户行:" prop="bankName">
                  <el-input v-model="form.bankName" placeholder="请输入开户行"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="银行行号:" prop="bankNo">
                  <el-input v-model="form.bankNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="银行账号:" prop="accountNo">
                  <el-input v-model="form.accountNo"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
                   label-width="90px">
            <el-form-item label="订单编号" prop="orderCode">
              <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" style="width: 260px;"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button icon="el-icon-plus" type="primary" size="mini" @click="submitSelectForm">添 加</el-button>
            </el-form-item>
          </el-form>
          <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
                    :max-height="tableMaxHeight">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="订单编号" align="center" prop="order.code"/>
            <el-table-column label="制单人" align="center" prop="createBy" width="110"/>
            <el-table-column label="交货日期" align="center" prop="deliveryDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总重量" align="center" prop="weight"/>
            <el-table-column label="订单金额" align="center" prop="money"/>
            <el-table-column label="采购剩余" align="center" prop="buyRemain"/>
            <el-table-column label="付款系数" align="center" prop="buyNumber" width="160" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.buyPrecent" :max="1" :precision="2" :step="0.01" size="mini" @change="calcBuyMoney(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="付款金额" align="center" prop="buyCount" width="220" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.buyMoneyTemp" size="mini"
                                 :max="scope.row.buyRemain"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"/>
        </el-card>
      </el-col>
    </el-row>


    <el-row style="padding-top: 20px;">
      <el-card class="box-card">
        <el-table :data="ironBuyList" ref="dragTable" row-key="id" v-loading="loadingRel" show-summary
                  :summary-method="getSummaries">
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column label="订单号" align="center" prop="orderCode"/>
          <el-table-column label="金额" align="center" prop="money"/>
          <el-table-column label="备注" align="center" prop="remark"/>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="140">
            <template slot-scope="scope">
              <el-popconfirm :title="`确认删除 `+scope.row.orderCode+` 数据项？`" @confirm="handleDeleteRel(scope.row)"
                             style="margin-left: 10px;">
                <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>


    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <caigou-detail-list ref="caigouDetailList" @ok="getList"></caigou-detail-list>
  </el-dialog>
</template>
<script>
import {addAction, getAction, accAdd, getById, updateAction, deleteAction, accMul} from '@/api/manage';
import moment from 'moment';
import {parseTime} from "@/utils/common";
import CaigouDetaiList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";
import CaigouDetailList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";

export default {
  name: "LvBuyIronMergeListForm",
  dicts: ["goods_type", "pay_material_status", "daohuo_status", "buy_pay_status", "goods_supplier", 'caigou_type'],
  components: {CaigouDetailList, CaigouDetaiList},
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingRel: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      dataList: [],
      selectRows: [],
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        cgallid: null,
        pageNum: 1,
        pageSize: 20,
        mainId: null,
        customerName: null,
        supplierName: null,
        params: {},
        orderByColumn: "a.create_time",
        isAsc: "desc",
      },
      queryParamsRel: {
        pageSizeZero: true,
        status: '0'
      },
      buy: {},
      // 表单校验
      rules: {
        applyTime: [{required: true, message: "请选择申请时间", trigger: "blur"}],
        totalMoney: [
          {required: true, message: "请输入申请付款金额", trigger: "blur"},
          {validator: this.totalMoneyValidator, trigger: 'blur'}],
        supplierId: [{required: true, message: "请选择供应商", trigger: "blur"}],
        bankName: [
          {required: true, message: "请输入开户行", trigger: "blur"}
        ],
        accountNo: [
          {required: true, message: "请输入银行账号", trigger: "blur"}
        ],
        ywType: [
          {required: true, message: "请选择采购类型", trigger: "blur"}
        ],
        depositMerge: [
          {required: true, message: "请选择运费是否合并付款", trigger: "blur"}
        ],
      },
      url: {
        list: '/orderIronRecord/orderIronRecord/list',
        relList: '/orderIronRecordBuy/orderIronRecordBuy/list',
        insertOrderRecordRel: '/orderIronRecordBuy/orderIronRecordBuy/insertOrderRecordRel',
        removeIronRecordRel: '/orderIronRecordBuy/orderIronRecordBuy/',
        goodsSupplierById: '/goodsSupplier/goodsSupplier/',
        addForIronRecordList: '/lvBuy/lvBuy/addForIronRecordList',
      },
      CS: {
        'text-align': 'center',  //文本居中
        'min-width': '250px',   //最小宽度
        'word-break': 'break-all'  //过长时自动换行
      },
      LS: {
        'color': '#000',
        'text-align': 'center',
        'font-weight': '600',
        'height': '40px',
        'min-width': '110px',
        'word-break': 'keep-all'
      },
      tableMaxHeight: window.innerHeight - 420,
      ironBuyList: [],
    };
  },
  created() {

  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.selectRows = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        buyId: null,
        applyTime: null,
        invoiceCode: null,
        invoicePhoto: null,
        totalMoney: null,
        paidMoney: null,
        remainMoney: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        ywType: "9",
      };
      this.resetForm("form");
    },

    totalMoneyValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('申请金额不能为0'));
      } else {
        callback();
      }
    },


    /** 提交按钮 */
    submitForm() {
      if(this.ironBuyList.length===0){
        this.$modal.msgError("请选择一条记录");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.ironRecordList = this.ironBuyList;
          addAction(this.url.addForIronRecordList, this.form).then(response => {
            this.$modal.msgSuccess("付款单申请成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },

    show(isDeposit, payApplyState) {
      this.reset();
      this.open = true;
      this.form.applyTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.queryParams.isDeposit = isDeposit;
      this.queryParams.payApplyState = payApplyState;
      // this.queryParams.arrivalStatus = "2";
      this.title = "铁附件采购单";
      this.getList();
      this.getIronBuyList();
    },

    /** 查询销售信息管理列表 */
    getList() {
      let that = this;
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        that.dataList = response.rows;
        that.total = response.total;
        that.loading = false;
      });
    },

    getIronBuyList() {
      let that = this;
      this.loadingRel = true;
      this.form.totalMoney = 0;
      getAction(this.url.relList, this.queryParamsRel).then(response => {
        that.ironBuyList = response.rows;
        for (let i = 0; i < that.ironBuyList.length; i++) {
          that.form.totalMoney = accAdd(that.form.totalMoney, that.ironBuyList[i].money);
        }
        that.loadingRel = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    caigou(row) {
      this.$refs.caigouDetailList.showcaigou(row);
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length;
      this.selectRows = selection;
      this.sumTotalMoney();
    },

    sumTotalMoney() {
      let totalMoney = 0;
      for (let i = 0; i < this.ids.length; i++) {
        for (let j = 0; j < this.dataList.length; j++) {
          if (this.ids[i] == this.dataList[j].id) {
            totalMoney = accAdd(totalMoney, this.dataList[j].shengyu)
          }
        }
      }
      this.form.totalMoney = totalMoney;
    },

    /** 提交按钮 */
    submitSelectForm() {
      let that = this;
      const ids = this.ids;
      if (ids == null || ids == '' || ids == 'undefined') {
        that.$modal.msgError("请选择一条记录");
      }
      for (let i = 0; i < that.selectRows.length; i++) {
        if (that.selectRows[i].buyMoneyTemp === 0) {
          that.$modal.msgError("付款金额不能为0");
          return;
        }
      }
      const params = Object.assign({});
      params.orderIronRecordList = that.selectRows;
      addAction(that.url.insertOrderRecordRel, params).then(response => {
        that.$modal.msgSuccess("添加成功");
        that.getIronBuyList();
        that.handleQuery();
      });
    },

    handleDeleteRel(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.removeIronRecordRel, ids).then(response => {
        this.getIronBuyList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "money") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    selectSupplier(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSsupplier;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.supplierName = arr[i].label;
            getById(this.url.goodsSupplierById, value).then(response => {
              that.form.bankName = response.data.bankName;//开户行
              that.form.accountNo = response.data.accountNo;//账号
              that.form.bankNo = response.data.bankNo;//行号
              //that.form.supplierId = response.data.id;//id
            });
          }
        }
      })
    },

    calcBuyMoney(row) {
      let that = this;
      let buyMoney = accMul(row.buyPrecent, row.buyRemain);
      that.$set(row, "buyMoneyTemp", buyMoney);
    },

  }
};
</script>

